import MenuExtraRender from '@/components/MenuExtraRender';
import RightContent from '@/components/RightContent';
import logo from '@/images/musiclogo.png';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { SettingDrawer } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';
import defaultSettings from '../config/defaultSettings';
import { errorConfig } from './requestErrorConfig';
import { currentUser as currentUserApi } from './services/home/api';

// const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/plaza';

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: HOMEAPI.CurrentUser;
  loading?: boolean;
  fetchUserInfo?: (type?: string, param?: any) => Promise<HOMEAPI.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async (type?: string, param?: any) => {
    let data: any = undefined;
    try {
      const isPass = WHITE_LIST.some((item: string) => {
        return window.location.href.includes(item);
      });
      if (type === 'login' || !isPass) {
        // 主动登录的和不在免登录白名单的才需要获取当前用户信息
        data = await currentUserApi(param);
      }
    } catch (error) {
      history.push(loginPath);
    }
    // 将用户信息缓存到本地
    if (data?.data) {
      localStorage.setItem('blogUserInfo', JSON.stringify(data.data));
    }
    return data;
  };
  // 判断当前是否已经登录 如果已经登录 就去本地缓存拿个人信息
  let currentUserLocal = localStorage.getItem('blogUserInfo') || null;
  if (currentUserLocal) {
    currentUserLocal = JSON.parse(currentUserLocal);
  }
  const currentUser = currentUserLocal || (await fetchUserInfo());
  return {
    fetchUserInfo,
    currentUser,
    settings: defaultSettings,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    logo,
    onPageChange: (location) => {
      const rge = new RegExp('^/admin|/login|(/spice)');
      if (rge.test(location?.pathname || '')) {
        // 去掉看板娘
        const waifu = document.getElementById('waifu')?.style;
        if (waifu) {
          waifu.display = 'none';
        }
      }
    },
    menuHeaderRender: undefined,
    rightContentRender: () => <RightContent />,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    menuExtraRender: ({ collapsed }) => <MenuExtraRender collapsed={collapsed} />,
    // 增加一个 loading 的状态
    childrenRender: (children, props) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <>
          {children}
        </>
      );
    },
    footerRender: () => {
      return (
        <a
          target="_blank"
          href="https://beian.miit.gov.cn/#/Integrated/index"
          rel="noreferrer"
          style={{ textAlign: 'center' }}
        >
          豫ICP备2023020281号
        </a>
      );
    },
    ...initialState?.settings,
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = {
  ...errorConfig,
};
